﻿/*
 * Cratos Desktop
 * Cratos WCF Service class
 * 
 * Copyright (c) 2011 Draco
 * 
 * This file is part of Cratos.
 * 
 * Cratos is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Cratos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cratos.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *       .==.        .==.
 *      //'^\\      //^'\\
 *     // ^ ^\(\__/)/^ ^^\\
 *    //^ ^^ ^/6  6\ ^^ ^ \\
 *   //^ ^^ ^/( .. )\^ ^ ^ \\
 *  // ^^ ^/\| V""V|/\^ ^ ^ \\
 * //^^/\/ /  '~~'  \ \/\^ ^ \\
 *  ------------------------------------
 *  HERE BE DRAGONS
 *  
 *  Johan Dercksen - johan@draco.co.za
 */
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;

using Cratos.Tools.General;
using Cratos.Desktop.CratosWcfService;
using System.ServiceModel;
using System.Xml;

namespace Cratos.Desktop
{
	/// <summary>
	/// Cratos WCF Static class
	/// </summary>
	public static class CWcfService
	{
		#region Class Constant declarations
		#endregion

		#region Class Event declarations
		/// <summary>
		/// Web Service online event
		/// </summary>
		public static event ServerStateEventHandler WebServiceOnline;

		/// <summary>
		/// Web Service offline event
		/// </summary>
		public static event ServerStateEventHandler WebServiceOffline;		
		#endregion

		#region Class Variable declarations
		private static bool										isUrlChanged = true;
		private static Uri										wcfServiceUri;
		private static CratosWcfServiceClient	wcfService;
		private static string									connectionName = "CratosDB";
		#endregion

		#region Class Constructors & Destructors
		#endregion

		#region Class Properties
		/// <summary>
		/// WCF Service URI
		/// </summary>
		public static Uri WcfServiceUri
		{
			get { return (wcfServiceUri); }
			set { wcfServiceUri = value; isUrlChanged = true; }
		}

		/// <summary>
		/// Database Connection Name
		/// </summary>
		public static string ConnectionName
		{
			get { return (connectionName); }
			set { connectionName = value; }
		}

		/// <summary>
		/// Service Property
		/// </summary>
		public static CratosWcfServiceClient WcfService
		{
			get
			{
				// Create and Setup the object if required
				if ((wcfService == null) || (isUrlChanged))
				{
					wcfService                  = new CratosWcfServiceClient();
					wcfService.Endpoint.Address = new System.ServiceModel.EndpointAddress(CWcfService.WcfServiceUri);

					// Reset the URL Changed indicator
					isUrlChanged = false;
				}

				// Return the Web Service object
				return (wcfService);
			}
		}

		#region Caching Properties
		/// <summary>
		/// Caching Enabled indicator
		/// </summary>
		public static bool CachingEnabled { get; set; }

		/// <summary>
		/// Cratos Cache object
		/// </summary>
		public static CratosCache Cache { get; set; }
		#endregion
		#endregion

		#region Class Methods
		/// <summary>
		/// Determine if the Web Service is available or not
		/// </summary>
		/// <returns>
		/// A boolean is returned indicating the success of the method
		/// </returns>
		public static bool Ping()
		{
			// Declare the required variables
			bool returnValue = false;

			try
			{
				// Ping the Web Service
				returnValue = CWcfService.WcfService.Ping();

				// Raise the Wb Service Online event
				OnWebServiceOnline();
			}
			catch (Exception runtimeException)
			{
				// Display the error message
				CratosHelper.LogMessage(CratosLogSeverity.Exception, "Cratos Proxy", "Runtime exception occurred", runtimeException, false);

				// Raise the offline event
				OnWebServiceOffline();
			}

			// Return to calling method
			return (returnValue);
		}

		/// <summary>
		/// Determine if the Database is available or not
		/// </summary>
		/// <param name="connectionName">Connection Name</param>
		/// <returns>
		/// A boolean is returned indicating the success of the method
		/// </returns>
		public static bool DatabaseAvailable()
		{
			// Declare the required variables

			// Return to calling method
			return (CWcfService.DatabaseAvailable(CWcfService.ConnectionName, DOCratosActionType.StoredProcedure));
		}

		/// <summary>
		/// Determine if the Database is available or not
		/// </summary>
		/// <param name="connectionName">Connection Name</param>
		/// <param name="actionType">Action Type</param>
		/// <returns>
		/// A boolean is returned indicating the success of the method
		/// </returns>
		public static bool DatabaseAvailable(string connectionName, DOCratosActionType actionType)
		{
			// Declare the required variables
			bool returnValue = false;

			try
			{
				//// Ping the Web Service
				returnValue = CWcfService.WcfService.DatabaseAvailable(connectionName, actionType);
			}
			catch (Exception runtimeException)
			{
				// Display the error message
				CratosHelper.LogMessage(CratosLogSeverity.Exception, "Cratos Proxy", "Runtime exception occurred", runtimeException, false);

				// Raise the offline event
				OnWebServiceOffline();
			}

			// Return to calling method
			return (returnValue);
		}

		/// <summary>
		/// Perform the Web Service action
		/// </summary>
		/// <param name="ctCratos">Cratos contract containing the relevant request information</param>
		/// <returns>Cratos contract containing the relevant response information</returns>
		public static CratosWcfContract PerformAction(CratosWcfContract ctCratos)
		{
			// Declare the required variables

			try
			{
				// Make a call to the Web Service
				ctCratos = CWcfService.WcfService.Cratos(ctCratos);
			}
			catch (Exception runtimeException)
			{
				// Determine if the WS is available
				if (Ping()) { throw new Exception(runtimeException.Message, runtimeException.InnerException); }
				else 
				{ 
					ctCratos.Errors = new string[] 
												{
													string.Format("[{0} - {1}] [{2}] {3}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
																																 "Cratos WCF Service",
																																 CratosLogSeverity.Exception,
																																 "Server Unavailable")
												};
				}
			}

			// Return to calling method
			return (ctCratos);
		}

		/// <summary>
		/// Get Server Date & Time
		/// </summary>
		/// <returns>Server Date & Time</returns>
		public static DateTime GetServerDateTime() { return (CWcfService.WcfService.GetServerDateTime()); }
		#endregion

		#region Class Support Methods
		/// <summary>
		/// Web Service Online event handler
		/// </summary>
		private static void OnWebServiceOnline()
		{
			// Raise the event if required
			if (WebServiceOnline != null) { WebServiceOnline(); };
		}

		/// <summary>
		/// Web Service Offline event handler
		/// </summary>
		private static void OnWebServiceOffline()
		{
			// Raise the event if required
			if (WebServiceOffline != null) { WebServiceOffline(); }
		}
		#endregion
	}
}
